package com.mjk.common.core.jdbc.service.parse.type.impl.sql;


import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.base.error.BizException;
import com.mjk.common.core.jdbc.datasource.DynamicDataSource;
import com.mjk.common.core.jdbc.service.parse.type.IBeeParse;
import com.mjk.common.core.jdbc.service.parse.type.impl.sql.type.SqlPraseType;
import com.mjk.common.core.jdbc.service.plus.idbservice.BaseDBService;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.ObjectUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQL语句解析类
 * @author Administrator
 *
 */
@Component
public class BeeSqlPrase implements IBeeParse {
	private final BaseDBService baseDBService;

	public BeeSqlPrase(BaseDBService baseDBService) {
		this.baseDBService = baseDBService;
	}

	/**
	 * 解析SQL语句
	 */
	@Override
	public Map<String,Object> parsing(String sqls,Map<String,Object> params) {
	//	BeeParseEntiy entity = new BeeParseEntiy();
		Map<String,Object> oldMap = new HashMap<>();
		if(ObjectUtils.isNotEmpty(params))
			oldMap.putAll(params);
		
		String[] sqlList = sqls.split(BeeCommonConstns.PARSING_SPLIT);
		for(String sql : sqlList) {
			paraseSql(sql, params);
		}
		
		params.keySet().removeAll(oldMap.keySet());
		return params;
	}
	/**
	 * 解析单条SQL语句
     */
	public void paraseSql(String sql ,Map<String,Object> params ) {
		if(ObjectUtils.isEmpty(sql)) {
			return;
		}
		sql = delNote(sql);//删除注释内容
		sql = sql.replace("\r", "").replace("\n", "");
		
		if(ObjectUtils.isEmpty(sql)) {
			return;
		}
	
		Pattern r = Pattern.compile(BeeCommonConstns.SET_PARAMS_MATH);
		Matcher m = r.matcher(sql);
		String leftKey = "";
		String databaseId = "";
		if(m.find()) {
			leftKey = m.group("key");
			databaseId = m.group("databaseId");
			sql = sql.replace(m.group(), "");
		}
		sql = SqlPraseType.getSql(sql, params);
		//判断是否是SQL语句，如果不是 不能执行
		Pattern sqlPattern = Pattern.compile(BeeCommonConstns.SQL_MATCH);
		Matcher sqlMatcher = sqlPattern.matcher(sql);
		if(!sqlMatcher.find()) {
			BizLogger.info(sql+"is not match sql syntax");
			return;
		}
		if(ObjectUtils.isEmpty(sql)) {
			BizLogger.info("invocker sql is not empty");
			return;
		}
		params.put("sql", sql);
		//切换数据源
		if(ObjectUtils.isNotEmpty(databaseId))
			DynamicDataSource.setDatabaseType(databaseId);
		List<Map<String,Object>> result = baseDBService.excuteSql(params);
		params.remove("sql");
		if(ObjectUtils.isNotEmpty(leftKey)) {
			//这里需要读leftkey进行判断，是否是下一层及的数据
			if(leftKey.contains(".")) {
				String[] tmps = leftKey.split(BeeCommonConstns.PARAMS_SPLIT);
				int index = 0;
				Map<String,Object> root = new HashMap<>();
                for (String tmp : tmps) {
                    Pattern pattern1 = Pattern.compile(BeeCommonConstns.SET_PARAMS_LIST_MATCH);
                    Matcher matcher1 = pattern1.matcher(tmp);
//					if(index < tmps.length-1) {
                    if (matcher1.find()) {//说明需要从数组中取值
                        int valueInBrackets = Integer.parseInt(matcher1.group(1));//序号
                        String name = matcher1.replaceAll("");//数组名称
                        if (!params.containsKey(name)) {
                            throw new BizException("params is not contain " + name + ",becouse having child ");
                        }
                        List<Map<String, Object>> list = (List<Map<String, Object>>) params.get(name);
                        root = list.get(valueInBrackets);
//						    }else {
//								if(!params.containsKey(tmps[i])) {
//									throw new BizException("params is not contain "+tmps[i]+",becouse having child ");
//								}
//								root = (Map<String, Object>) params.get(tmps[i]);
//						}
                    }
                    if (index == tmps.length - 1) {
                        setParams(tmp, root, result);
                    }
                    index++;
                }
			}else {
				setParams(leftKey,params,result);
			}
		}
	}
	
	public void setParams(String leftKey,Map<String,Object> params,List<Map<String,Object>> result) {
		Pattern keyPattern = Pattern.compile(BeeCommonConstns.SET_PARAMS_LIST);
		Matcher key = keyPattern.matcher(leftKey);
		if(key.find()) {//如果是list
			params.put(leftKey, result);
		}else {//否则都是OBJ
			if(CollectionUtils.isEmpty(result)) {
				params.put(leftKey, "");
			}else {
				params.put(leftKey, result.get(0));
			}
		}
	}
	
	public static String delNote(String sql) {
		if(ObjectUtils.isEmpty(sql)) {
			return "";
		}
        return sql.replaceAll(BeeCommonConstns.NOTE_MATCH, "");
	}	
	
}
